package com.qf.android.sport.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.qf.android.sport.BR;
import com.qf.android.sport.R;
import com.qf.android.sport.adapter.Ablumadapter;
import com.qf.android.sport.adapter.TwoRecyclerAdapter;
import com.qf.android.sport.callback.HttpService;
import com.qf.android.sport.databinding.ActivityTwoNewBinding;
import com.qf.android.sport.entity.news.Contest;
import com.qf.android.sport.entity.news.Recs;
import com.qf.android.sport.entity.news.Root;
import com.qf.android.sport.entity.news.TwoData;
import com.qf.android.sport.entity.news.TwoNew;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TwoNewActivity extends AppCompatActivity implements View.OnClickListener, Callback<TwoNew> {
    private ActivityTwoNewBinding binding;
    private TwoRecyclerAdapter<Object> adapter;
    private Ablumadapter<Object> adapter1;
    private HttpService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_two_new);
        binding.back.setOnClickListener(this);
        Intent intent = getIntent();
        long id = intent.getLongExtra("id", 0);
        HashMap<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        HashMap<Class<?>, Pair<Integer, Integer>> map1 = new HashMap<>();

        map.put(TwoData.class, Pair.create(R.layout.two_item, BR.twodata));
        map.put(Contest.class, Pair.create(R.layout.two_item, BR.twodata));

        map1.put(Recs.class, Pair.create(R.layout.ablum_item, BR.recs));
        map1.put(TwoData.class, Pair.create(R.layout.two_item, BR.twodata));


        adapter = new TwoRecyclerAdapter<Object>(binding.getRoot().getContext(), new ArrayList<>(), map);
        adapter1 = new Ablumadapter<Object>(binding.getRoot().getContext(), new ArrayList<>(), map1);

        binding.twoList.setAdapter(adapter);
        binding.oneList.setAdapter(adapter1);
        //匹配字符date
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
                    private final SimpleDateFormat SDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);

                    @Override
                    public void write(JsonWriter out, Date value) throws IOException {
                        if (value == null) {
                            out.nullValue();
                        } else {
                            out.value(SDF.format(value));
                        }
                    }

                    @Override
                    public Date read(JsonReader in) throws IOException {
                        if (in.hasNext()) {
                            String s = in.nextString();
                            try {
                                return SDF.parse(s);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        return null;
                    }
                }).create();
        service = new Retrofit.Builder()
                .baseUrl("http://api.lifxapi.com/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
                .create(HttpService.class);
        service.getNew("view", id).enqueue(this);
        new Retrofit.Builder()
                .baseUrl("http://api.lifxapi.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(HttpService.class).getroot(id).enqueue(new Callback<Root>() {
            @Override
            public void onResponse(Call<Root> call, Response<Root> response) {
                Log.d("11111", "onResponse: " + response.body().getData().getRecs().get(0).getTitle());
                Log.d("11111", "onResponse: " + response.body().getData().getRecs().get(0).getImage());
                List<Recs> recs = response.body().getData().getRecs();
                if (recs != null && recs.size() != 0) {
                    adapter1.addAll(recs);
                }
            }

            @Override
            public void onFailure(Call<Root> call, Throwable t) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        finish();
    }

    @Override
    public void onResponse(Call<TwoNew> call, Response<TwoNew> response) {
        TwoNew body = response.body();
        String content = body.getData().getText_content();
        adapter.add(body.getData());
        List<String> images = body.getData().getText_images();
        Matcher matcher = Pattern.compile("\\$\\{lx-(\\w+)-?(\\d*)\\}").matcher(content);
        StringBuffer buffer = new StringBuffer("<style>img{max-width:100%}</style>");
        while (matcher.find()) {
            switch (matcher.group(1)) {
                case "br":
                    matcher.appendReplacement(buffer, "<br/>");
                    break;
                case "image":
                    matcher.appendReplacement(buffer, String.format(Locale.getDefault(), "<img src=\"%s\"/>", images.get(Integer.parseInt(matcher.group(2)))));
                    break;
            }


        }
        matcher.appendTail(buffer);
        binding.web.loadData(buffer.toString(), "text/html; charset=utf-8;", "UTF-8");
    }

    @Override
    public void onFailure(Call<TwoNew> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(this, "下载失败", Toast.LENGTH_SHORT).show();
    }
}
